<?php

namespace Api\Controller;

use Think\Controller;

// 跨域
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:x-requested-with, content-type,token');

require_once 'vendor/autoload.php';
// 导入对应产品模块的client
use TencentCloud\Sms\V20210111\SmsClient;
// 导入要请求接口对应的Request类
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;



class TenderOrderController extends Controller
{

    // 获取支付状态
    function get_pay_state()
    {
        $id = $_POST['id'];
        if ($id == null) $this->ajaxReturn(['state' => 0, 'info' => '请检查订单号']);

        $tender_order = M('tender_order')->find($id);

        $wx_pay  = new WxpayController();
        $res = $wx_pay->get_pay_order($tender_order['pay_number']);

        $state = 0;
        $info = $res['trade_state_desc'];
        if ($res['trade_state'] == 'SUCCESS') {
            $state = 1;
            $info = '支付成功';
        }
        $this->ajaxReturn(['state' => $state, 'info' => $info]);
    }

    /**
     * 字符串截取并且超出显示省略号
     * @param $str 内容
     * @param $len 长度
     * @return string
     */
    function subtext($str, $len)
    {
        if (strlen($str) > $len) {
            $str = mb_substr($str, 0, $len) . '...';
        }
        return $str;
    }

    // 获取微信支付二维码
    function get_wxpay_qrcode()
    {
        $id = $_POST['id'];
        if ($id == null) $this->ajaxReturn(['state' => 0, 'info' => '请检查订单号']);
        $tender_order = M('tender_order')->find($id);

        // 关闭之前订单
        if ($tender_order['pay_number']) {
            $wx_pay  = new WxpayController();
            $res = $wx_pay->close_pay_order($tender_order['pay_number']);
        }


        // 生成订单号
        $characters = '0123456789';
        $tender_order['pay_number'] = '';
        for ($i = 0; $i < 15; $i++) $tender_order['pay_number'] .= $characters[rand(0, strlen($characters) - 1)];
        M('tender_order')->save($tender_order);
        $tender_order = M('tender_order')->find($id);

        $wx_pay  = new WxpayController();
        $res = $wx_pay->native($tender_order['pay_number'], $this->subtext($tender_order['name'], 30), $tender_order['money'] * 100, $this->payConfig['wx_notification_url'] . '/admin/api/tender_order/asyn_save_wx_order_number', json_encode(['pay_number' => $tender_order['pay_number']]));

        $this->ajaxReturn(['state' => 1, 'info' => '获取成功', 'data' =>  $res['code_url']]);
    }

    // 异步更新微信订单消息
    function asyn_save_wx_order_number()
    {
        $data = file_get_contents('php://input'); //接收来自微信的回调数据
        $data = json_decode($data, true);
        $wx_pay  = new WxpayController();
        $res = $wx_pay->decrypt_to_string($data['resource']['associated_data'], $data['resource']['nonce'], $data['resource']['ciphertext']);
        $res = json_decode($res, true);

        if ($res['trade_state'] == 'SUCCESS') {
            // 更新支付订单号
            $save['pay_state'] = 1;
            M('tender_order')->where('pay_number="' . $res['out_trade_no'] . '"')->save($save);
        }
        file_put_contents('./payCallBack/wx.json', json_encode($data) . "\n\r", FILE_APPEND); //将接收到的数据存入wxCallBack.json文件中
    }
    // 发送手机号验证短信验证码
    function send_check_phone_sms()
    {
        // 检查
        $arr = ['phone'];
        foreach ($arr as $val) if ($_POST[$val] == null) $this->ajaxReturn(['state' => 0, 'info' => '请检查数据是否输入正确']);
        $code = rand(1001, 9999);
        session('code', $code);
        $res = $this->send_sms($_POST['phone'], [strval($code)], '1906148');
        if ($res['Code'] == 'Ok') {
            $this->ajaxReturn(['state' => 1, 'info' => '发送成功', 'code' => md5($code)]);
        } else {
            $this->ajaxReturn(['state' => 0, 'info' => '发送失败', 'data' => $res]);
        }
    }


    //  发送中标短信通知
    function send_win_bid_sms()
    {
        // 检查
        $arr = ['id'];
        foreach ($arr as $val) if ($_POST[$val] == null) $this->ajaxReturn(['state' => 0, 'info' => '请检查数据是否输入正确']);
        $tender_order = M('tender_order')->find($_POST['id']);
        $res = $this->send_sms($tender_order['customer_phone'], [$tender_order['name'], $tender_order['number']], '1877228');
        if ($res['Code'] == 'Ok') {
            $this->ajaxReturn(['state' => 1, 'info' => '中标短信发送成功']);
        } else {
            $this->ajaxReturn(['state' => 0, 'info' => '中标短信发送失败', 'data' => $res]);
        }
    }

    // 发送腾讯云短信 单条
    function send_sms($phone, $param, $templateId)
    {
        // SecretId-SecretKey
        $cred = new Credential("AKIDrh2HQO9kCanmbGiBHE1hHuNipiT2XrIb", "EICuTpy9IKH8ykR2UoywkIm8NSQJ0YOB");
        $client = new SmsClient($cred, "ap-guangzhou");
        $req = new SendSmsRequest();
        // 短信appid
        $req->SmsSdkAppId = "1400840549";
        // 签名
        $req->SignName = "宁波建兴招标有限公司";
        // 模版id
        $req->TemplateId = $templateId;
        // 参数
        $req->TemplateParamSet = $param;
        // 发送号码
        $req->PhoneNumberSet = array("+86" . $phone);
        $res = $client->SendSms($req);
        return json_decode($res->toJsonString(), true)['SendStatusSet'][0];
    }
    // 搜索标书订单
    function get_tender_order()
    {
        // 分页
        $page = $_POST['page'];
        $current = $page['current'] ? $page['current'] : 1;
        $size = $page['size'] ? $page['size'] : 10;
        // 条件
        $query = $_POST['query'];

        // 单个
        if ($query['id']) $where['id'] = $query['id'];
        // 项目名称
        if ($query['name']) $where['name'] = ['like', '%' . $query['name'] . '%'];
        // 项目编号
        if ($query['number']) $where['number'] = ['like', '%' . $query['number'] . '%'];
        // 购买单位
        if ($query['customer_unit']) $where['customer_unit'] = ['like', '%' . $query['customer_unit'] . '%'];
        // 联系人
        if ($query['customer_name']) $where['customer_name'] = ['like', '%' . $query['customer_name'] . '%'];
        // 手机号
        if ($query['customer_phone']) $where['customer_phone'] = ['like', '%' . $query['customer_phone'] . '%'];
         // 下单时间
         if ($query['addtime']) $where['addtime'] = ['like', '%' . $query['addtime'] . '%'];

        $count = M('tender_order')->where($where)->count();
        $data = M('tender_order')->where($where)->order('addtime desc')->limit(($size * $current) - $size, $size)->select();

        $this->ajaxReturn(['state' => 1, 'info' => '搜索成功', 'data' => $data, 'count' => intval($count)]);
    }




    // 删除标书订单
    function del_tender_order()
    {
        // 检查
        $arr = ['id'];
        foreach ($arr as $val) if ($_POST[$val] == null) $this->ajaxReturn(['state' => 0, 'info' => '请检查数据是否输入正确']);

        M('tender_order')->delete(implode(',', $_POST['id']));
        $this->ajaxReturn(['state' => 1, 'info' => '删除成功']);
    }

    // 添加修改标书
    function handle_tender_order()
    {
        // 检查
        $arr = [
            'name', 'money', 'number', 'customer_type',
            'customer_name', 'customer_email', 'customer_unit', 'customer_phone',
            'business_license', 'invoice_type', 'invoice_address_phone',
            'taxpayer_identification_number', 'invoice_bank_number'
        ];
        foreach ($arr as $val) if ($_POST[$val] == null) $this->ajaxReturn(['state' => 0, 'info' => $val . '请检查数据是否输入正确']);

        if ($_POST['id']) {
            $info = '修改成功';
            M('tender_order')->save($_POST);
        } else {
            $info = '添加成功';
            $_POST['addtime'] =  date("Y-m-d H:i:s");
            M('tender_order')->add($_POST);
        }
        $this->ajaxReturn(['state' => 1, 'info' => $info]);
    }


    // 获取项目列表
    function get_project()
    {
        // 分页
        $page = $_POST['page'];
        $current = $page['current'] ? $page['current'] : 1;
        $size = $page['size'] ? $page['size'] : 10;
        // 条件
        $query = $_POST['query'];

        // 单个
        if ($query['id']) $where['id'] = $query['id'];

        // 项目名称
        if ($query['name']) $where['title'] = ['like', '%' . $query['name'] . '%'];

        // 编号
        if ($query['number']) $where['field'] = ['like', '%' . $query['number'] . '%'];

        // 必须有标书
        $where['images'] = ['NEQ', ''];
        $where['module_id'] = ['EQ', 36];

        // 最后购买期限 description
        $where['description'] = ['EGT', date("Y-m-d")];

        $count = M('ak_content')->where($where)->count();
        $data = M('ak_content')->where($where)->order('addtime desc')->limit(($size * $current) - $size, $size)->select();

        // json格式字段转换成对象
        foreach ($data as  $key => $val) {
            $data[$key]['images'] = json_decode(html_entity_decode($val['images']), true);
            $data[$key]['field'] = json_decode($val['field'], true);
            $data[$key]['field']['money'] = (float)$data[$key]['field']['money'];
        }
        // 格式化
        $list = [];
        foreach ($data as  $val) {
            $arr = [];
            $arr['title'] = $val['title'];
            $arr['money'] = $val['field']['money'];
            $arr['win_bid_template'] = $val['field']['win_bid'];
            $arr['number'] = $val['field']['number'];
            if ($val['images']) {
                unset($val['images'][0]['href']);
                $arr['file'] = $val['images'][0];
            }
            array_push($list, $arr);
        }
        $data = $list;
        $this->ajaxReturn(['state' => 1, 'info' => '搜索成功', 'data' => $data, 'count' => intval($count)]);
    }

    // 所有函数入口
    function _initialize()
    {
        // 白名单
        $whitelist = ['get_project', 'handle_tender_order', 'send_check_phone_sms', 'get_tender_order', 'get_wxpay_qrcode', 'asyn_save_wx_order_number', 'get_pay_state'];
        $url = explode('/', $_SERVER['PATH_INFO']);
        $method = $url[count($url) - 1];
        // 需要验证token
        if (!in_array($method, $whitelist)) {
            $token = $_SERVER['HTTP_TOKEN'];
            $where['token'] = $token;
            $where['expire_time'] = ['gt', date("Y-m-d H:i:s")];
            $login = M('login')->where($where)->find();
            if (!$login) $this->ajaxReturn(['state' => 0, 'info' => '登录已失效 , 请重新登录']);
        }

        // 引入支付配置文件
        $this->payConfig = @include_once CONF_PATH . 'payConfig.php';
    }


    /**
     * 执行POST请求
     * 
     * @param string $url 请求的URL
     * @param array|string $data 可选 POST请求的数据 ，默认为空数组
     * @param array $headers 可选，要添加的头部信息数组，默认为空数组
     * @return string 响应结果
     */
    function httpPostRequest($url, $data = [], $headers = [])
    {
        $ch = curl_init($url);

        // 设置请求方法为POST
        curl_setopt($ch, CURLOPT_POST, 1);

        // 设置POST数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // 添加头部信息
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        // 设置选项以将响应作为字符串接收
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行请求
        $response = curl_exec($ch);

        // 关闭curl句柄
        curl_close($ch);

        // 返回响应
        return $response;
    }


    /**  
     * 函数的含义说明：CURL发送get请求    获取数据
     * 
     * @access public 
     * @param str $url 发送接口地址  https://api.douban.com/v2/movie/in_theaters?city=广州&start=0&count=10
     * @return  返回json数据
     */
    public function httpGetRequest($url, $headers = [])
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        // array_push($headers, 'Content-Type: application/json; charset=utf-8');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $output = curl_exec($curl);     //返回api的json对象
        // 转数组
        $output = json_decode($output, true);
        $output['httpCode'] = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //关闭URL请求
        curl_close($curl);
        return $output;
    }
}
